<template>
  <div class="app">
    <van-nav-bar
      title="球桌预约"
      left-text=""
      left-arrow
      @click="backlink()"
    ></van-nav-bar>
    <div class="datebox">
      <div class="boxtitle">
        <div class="shuxian"></div>
        <div class="datetitle">预约时间</div>
      </div>
      <van-field
        v-model="timevalue"
        is-link
        readonly
        label="时间段"
        placeholder="请选择起始时间"
        @click="openTimePicker"
      />
      <van-popup v-model:show="timepickershow" round position="bottom">
        <van-cascader
          :model-value="cascaderValue"
          title="请选择所在地区"
          :options="timeoptions"
          @close="timepickershow = false"
          @finish="onFinish"
        />
      </van-popup>
    </div>
    <div class="datebox">
      <div class="boxtitle">
        <div class="shuxian"></div>
        <div class="datetitle">球桌类型</div>
      </div>
      <div class="inbox">
        <div class="store_name">{{ this.clubinfo.store_name }}</div>
        <van-divider style="border-color: black; margin: 10px auto" />
        <div
          style="
            display: flex;
            justify-content: space-between;
            align-items: center;
          "
        >
          <div class="table_number">
            {{ this.clubinfo.type + "-" + this.clubinfo.table_number }}号桌
          </div>
          <div class="table_price">单价：{{ this.clubinfo.price }}元/小时</div>
        </div>
      </div>
      <div class="yuyuejin">
        <div style="font-size: 18px">预约金</div>
        <div style="font-size: 19px; color: #f7a440">
          ￥{{ this.clubinfo.deposit_amount }}元
        </div>
      </div>
    </div>
    <div class="datebox">
      <div class="boxtitle">
        <div class="shuxian"></div>
        <div class="datetitle">预约规则</div>
      </div>
      <div v-html="yuyuerule" class="rules"></div>
    </div>
    <div class="datebox">
      <div class="boxtitle">
        <div class="shuxian"></div>
        <div class="datetitle">支付方式</div>
      </div>
      <div>
        <van-radio-group v-model="checked">
          <van-cell-group inset>
            <van-cell
              clickable
              @click="checked = '1'"
              style="padding: 10px 2px"
            >
              <template #title>
                <div style="display: flex; align-items: center">
                  <icon-svg
                    icon-class="paycard"
                    icon-color="#304056"
                    class="payicon"
                  ></icon-svg>
                  <span class="custom-title">储值卡支付</span>
                </div>
              </template>
              <template #right-icon>
                <van-radio name="1" />
              </template>
            </van-cell>
            <van-cell
              clickable
              @click="checked = '2'"
              style="padding: 10px 2px"
            >
              <template #title>
                <div style="display: flex; align-items: center">
                  <icon-svg
                    icon-class="weixinpay"
                    icon-color="#304056"
                    class="payicon"
                  ></icon-svg>
                  <span class="custom-title">微信支付</span>
                </div>
              </template>
              <template #right-icon>
                <van-radio name="2" />
              </template>
            </van-cell>
            <van-cell
              clickable
              @click="checked = '3'"
              style="padding: 10px 2px"
            >
              <template #title>
                <div style="display: flex; align-items: center">
                  <icon-svg
                    icon-class="alipay"
                    icon-color="#304056"
                    class="payicon"
                  ></icon-svg>
                  <span class="custom-title">支付宝支付</span>
                </div>
              </template>
              <template #right-icon>
                <van-radio name="3" />
              </template>
            </van-cell>
          </van-cell-group>
        </van-radio-group>
      </div>
    </div>
    <div class="btnbox">
      <div style="font-size: 19px; color: #f7a440; margin-left: 15px">
        ￥{{ this.clubinfo.deposit_amount }}元
      </div>
      <van-button
        type="primary"
        round
        class="yuyuebtn"
        @click="postReservation"
      >
        预约
      </van-button>
    </div>
  </div>
</template>

<script>
import { tablereservation } from "@/http/request.js";
import { useStore } from "@/store/index.js";
import { showToast } from "vant";
export default {
  data() {
    return {
      clubinfo: {},
      checked: 1,
      yuyuerule:
        "1.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>2.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>3.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>4.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>5.xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</p>",
      deposit_amount: 0,
      sinuoke_price: 0,
      zhongba_price: 0,
      baojian_price: 0,
      timevalue: "",
      cascaderValue: [],
      timepickershow: false,
      timeoptions: [],
      formdata: {
        store_id: "",
        start_time: "",
        end_time: "",
        t_id: "",
        t_number: "",
        user_id: "",
        t_grade: "",
        city: "",
      },
    };
  },
  methods: {
    async initTable() {
      if (this.clubinfo.grade == 1) {
        this.clubinfo.price = this.clubinfo.zhongba_price;
        this.clubinfo.deposit_amount =
          (this.clubinfo.zhongba_price * this.clubinfo.deposit_amount) / 60;
        this.clubinfo.type = "中巴";
      } else if (this.clubinfo.grade == 2) {
        this.clubinfo.price = this.clubinfo.baojian_price;
        this.clubinfo.deposit_amount =
          (this.clubinfo.baojian_price * this.clubinfo.deposit_amount) / 60;
        this.clubinfo.type = "包间";
      } else if (this.clubinfo.grade == 3) {
        this.clubinfo.price = this.clubinfo.sinuoke_price;
        this.clubinfo.deposit_amount =
          (this.clubinfo.sinuoke_price * this.clubinfo.deposit_amount) / 60;
        this.clubinfo.type = "斯诺克";
      }
    },
    sliceTime(startTime, endTime, sliceSize) {
      let result = [];
      let current = startTime;
      while (current < endTime) {
        result.push(current);
        let [hours, minutes, seconds] = current.split(":").map(Number);
        let nextMinutes = minutes + sliceSize;
        let nextHours = hours + Math.floor(nextMinutes / 60);
        nextMinutes = nextMinutes % 60;
        nextHours = nextHours % 24;
        current = `${String(nextHours).padStart(2, "0")}:${String(
          nextMinutes
        ).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`;
      }
      // 添加结束时间，确保包含 endTime
      result.push(endTime);
      return result;
    },
    initTime(item) {
      this.timeoptions = [
        {
          text: "空闲场次",
          value: "free",
          children: [],
        },
        {
          text: "火爆场次",
          value: "busy",
          children: [],
        },
      ];

      if (item.free_start_time != null) {
        this.populateTimeOptions(
          this.timeoptions[0],
          item.free_start_time,
          item.free_end_time,
          item.free_slice_time
        );
      } else {
        this.timeoptions[0].children.push({ text: "没有可用选项", value: "" });
      }
      if (item.busy_start_time != null) {
        this.populateTimeOptions(
          this.timeoptions[1],
          item.busy_start_time,
          item.busy_end_time,
          item.busy_slice_time
        );
      } else {
        this.timeoptions[1].children.push({ text: "没有可用选项", value: "" });
      }
    },
    openTimePicker() {
      this.timepickershow = true;
    },
    populateTimeOptions(timeOption, startTime, endTime, sliceTime) {
      let time = this.sliceTime(startTime, endTime, sliceTime);
      for (let i = 0; i < time.length; i++) {
        let currentStartTime = time[i];
        let children = [];
        for (let j = i + 1; j < time.length; j++) {
          children.push({ text: time[j], value: time[j] });
        }
        timeOption.children.push({
          text: currentStartTime,
          value: currentStartTime,
          children:
            children.length === 0
              ? [{ text: "没有可用选项", value: "" }]
              : children,
        });
      }
    },
    isTimeok(value) {
      var currentTime = new Date(); // 获取当前时间
      var time1 = new Date(
        currentTime.getFullYear(),
        currentTime.getMonth(),
        currentTime.getDate(),
        value.selectedOptions[1].text.split(":")[0],
        value.selectedOptions[1].text.split(":")[1],
        value.selectedOptions[1].text.split(":")[2]
      );
      var time2 = new Date(
        currentTime.getFullYear(),
        currentTime.getMonth(),
        currentTime.getDate(),
        value.selectedOptions[2].text.split(":")[0],
        value.selectedOptions[2].text.split(":")[1],
        value.selectedOptions[2].text.split(":")[2]
      );
      var time1Diff = (time1 - currentTime) / (1000 * 60);
      if (time1.getTime() > currentTime.getTime()) {
        var timeDiff = time2 - time1;
        var minutesDiff = timeDiff / (1000 * 60);
        if (value.selectedOptions[0].value == "free") {
          if (time1Diff < this.clubinfo.free_pre_reservation) {
            if (minutesDiff < this.clubinfo.free_minimum_reservation_time) {
              showToast(
                `空闲场次最少预约 ${this.clubinfo.free_minimum_reservation_time} 分钟哦`
              );
              return false;
            } else {
              this.clubinfo.start_time = time1;
              this.clubinfo.end_time = time2;
              return true;
            }
          } else {
            showToast(
              `空闲场次在 ${this.clubinfo.free_pre_reservation} 分钟前才可预约哦`
            );
            return false;
          }
        } else if (value.selectedOptions[0].value == "busy") {
          if (time1Diff < this.clubinfo.busy_pre_reservation) {
            if (minutesDiff < this.clubinfo.busy_minimum_reservation_time) {
              showToast(
                `火爆场次最少预约 ${this.clubinfo.busy_minimum_reservation_time} 分钟哦`
              );
              return false;
            } else {
              this.clubinfo.start_time = time1;
              this.clubinfo.end_time = time2;
              return true;
            }
          } else {
            showToast(
              `火爆场次在 ${this.clubinfo.busy_pre_reservation} 分钟前才可预约哦`
            );
            return false;
          }
        }
      } else if (time1.getTime() < currentTime.getTime()) {
        showToast("开始时间不能早于当前时间哦");
      }
    },
    onFinish(value) {
      this.timepickershow = false;
      if (this.isTimeok(value)) {
        this.timevalue = value.selectedOptions
          .map((option) => option.text)
          .join("-");
        this.clubinfo.start_time = value.selectedOptions[1].text
          .toLocaleString()
          .replace(/\//g, "-");
        this.clubinfo.end_time = value.selectedOptions[2].text
          .toLocaleString()
          .replace(/\//g, "-");
        this.clubinfo.grade = this.clubinfo.grade;
        this.clubinfo.table_id = this.clubinfo.table_id;
        this.clubinfo.t_number = this.clubinfo.table_number;
      } else {
        this.timevalue = "";
      }
    },
    postReservation() {
      const store = useStore();
      const userinfo = store.getUserStoreinfo;
      const city = store.getStoreCityName;
      this.formdata.user_id = userinfo.id;
      this.formdata.city = city;
      this.formdata.store_id = parseInt(this.clubinfo.store_id);
      this.formdata.start_time = this.clubinfo.start_time;
      this.formdata.end_time = this.clubinfo.end_time;
      this.formdata.t_id = this.clubinfo.table_id;
      this.formdata.t_number = this.clubinfo.t_number;
      this.formdata.t_grade = this.clubinfo.grade;
      tablereservation(this.formdata).then((res) => {
        showToast(res.msg);
        if (res.code == 0) {
          const store = useStore();
          let yuyueorder = store.getYuyueingOrder;
          yuyueorder.table.push(res.data);
          for (var i = 0; i < yuyueorder.table.length; i++) {
            if (yuyueorder.table[i].t_grade == 1) {
              yuyueorder.table[i].level = "中巴";
            } else if (yuyueorder.table[i].t_grade == 2) {
              yuyueorder.table[i].level = "包间";
            } else if (yuyueorder.table[i].t_grade == 3) {
              yuyueorder.table[i].level = "斯诺克";
            }
          }
          store.setYuyueingOrder(yuyueorder);
          this.$router.push("/tableyuyueing");
        }
      });
    },
    backlink() {
      this.$router.back();
    },
  },
  created() {
    this.clubinfo = JSON.parse(this.$route.params.clubinfo);
    this.initTable(this.clubinfo.store_id);
    this.initTime(this.clubinfo);
  },
};
</script>

<style scoped>
.app {
  margin: 0;
  padding: 0;
  width: 100%;
  background-color: #f2f3f5;
}
.datebox {
  width: 100%;
  margin: 15px auto;
  background-color: white;
  padding: 8px 8px 8px 8px;
  box-sizing: border-box;
}
.boxtitle {
  display: flex;
  margin-left: 20px;
  align-items: center;
}
.shuxian {
  width: 3px;
  height: 20px;
  background-color: #5e94fe;
  border-radius: 3px;
}
.datetitle {
  font-size: 18px;
  line-height: 25px;
  margin-left: 4px;
}
.inbox {
  width: 85%;
  margin: 5px auto;
  padding: 12px;
  background-color: #f2f3f5;
  border-radius: 5px;
}
.inbox .store_name {
  font-size: 19px;
}
.inbox .table_number {
  font-size: 24px;
  font-weight: 550;
}
.inbox .table_price {
  font-size: 18px;
}
.yuyuejin {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 90%;
  margin: 10px auto;
}
.rules {
  width: 90%;
  font-size: 18px;
  margin-left: 15px;
  margin-top: 5px;
  white-space: normal; /* 允许内容根据需要换行 */
  overflow-wrap: break-word; /* 在必要时断字 */
  word-break: keep-all; /* 在中英文混合时，尽量避免在中文字符间断行 */
}
.payicon {
  width: 30px;
  height: 30px;
  margin-right: 5px;
}
.btnbox {
  width: 100%;
  margin: 10px auto;
  background-color: white;
  height: 60px;
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-sizing: border-box;
}
.yuyuebtn {
  width: 90px;
  height: 40px;
  margin-right: 15px;
}
</style>